<template>
  <div class='news-wrapper'>
    <!-- 展示请在微信环境打开 -->
    <section class='news-invalid-onlywechat' v-if='invalidForWechat && !loading'>
      请在微信环境打开
    </section>
    <!-- 展示无权限访问 -->
    <section class='news-invalid-visit' v-if='invalidForVisit && !loading'>
      当前为受保护内容，您无权访问
    </section>
    <!-- 正文展示 -->
    <section class='news-detail'
            :class='{noCopy: actionPermit.forbidCopy}'
             v-if='!invalidForWechat && !invalidForVisit && !loading'>
      <div class='detail-title'>{{news.articleTitle}}</div>
      <div class='detail-subtitle'>
        <span class='sub-item sub-icon'>原创</span>
        <span class='sub-item sub-time'>{{news.uploadTime.slice(0, 10)}}</span>
        <span class='sub-item sub-author'>{{news.author}}</span>
        <span class='sub-item sub-wechat' @click='showQrCode'>{{wechatName}}</span>
      </div>
      <div class='detail-content editor-content' v-html='news.content'></div>
      <div class='detail-footer'
           v-if='actionPermit.showReadNumber ||
                 actionPermit.showCollect ||
                 actionPermit.showThumbUp ||
                 actionPermit.allowedCollect ||
                 actionPermit.allowedThumbUp'>
        <div class='detail-data'>
          <div class='data-item' v-show='actionPermit.showReadNumber'>
            <span class='item-label'>阅读</span>
            <span class='item-content'>{{actionCount.readNum + actionCount.brushNum || 0}}</span>
          </div>
          <div class='data-item' v-show='actionPermit.showCollect'>
            <span class='item-label'>收藏</span>
            <span class='item-content'>{{actionCount.collectNum || 0}}</span>
          </div>
          <div class='data-item' v-show='actionPermit.showThumbUp'>
            <span class='item-label'>点赞</span>
            <span class='item-content'>{{actionCount.thumbUpNum || 0}}</span>
          </div>
        </div>
        <!-- 显示阅读数、收藏数、点赞、收藏 -->
        <div class='detail-handle'>
          <div class='article-collect'
              :class='{isCollected: hasCollected}'
              v-if='isWxClient && actionPermit.allowedCollect'
              @click='collectArticle()'>
            <span class='iconfont'>{{hasCollected ? '&#xe667;' : '&#xe669;' }}</span><span>收藏</span>
            <span :class='{iconfont: true, dynamic: true, move: isMove}'>&#xe667;</span>
          </div>
          <div class='article-thumbUp'
              :class='{isThumbUped: hasThumbUp}'
              v-if='isWxClient && actionPermit.allowedThumbUp'
              @click='praiseArticle()'>
            <span class='iconfont'>{{hasThumbUp ? '&#xe665;' : '&#xe666;'}}</span><span>点赞</span>
            <span :class='{iconfont: true, dynamic: true, move: isMove1}'>&#xe665;</span>
          </div>
        </div>
      </div>
    </section>
    <!-- 留言 -->
    <section class='detail-msg' v-if='isWxClient && actionPermit.allowedComment && !loading'>
      <div class='msg-box' @click='showCommentDialog'>写下你的留言</div>
    </section>
    <!-- 留言输入框二 -->
    <div class='article-comment-inputbox-wrapper' v-if='startComment'>
      <div class='article-comment-inputbox'>
        <div class='inputbox-title'>写留言
          <span class='iconfont cancel-input' @click='cancelComment()'>&#xe63e;</span>
        </div>
        <textarea class='inputbox-content'
                  v-model.trim="msgContent"
                  placeholder="留言将由运营者审核后展示"
                  @blur='hideCommentBox'
                  ref='commentRef'>
        </textarea>
        <div class='inputbox-submit' :class='{active: msgContent}' @click='submitComment'>提 交</div>
      </div>
    </div>
    <!-- 图片预览 -->
    <van-image-preview
      v-model="showPreview"
      :start-position='currImgIndex'
      ref='imgPreview'
      :images="imageList"
      @change="onChange"
      closeable>
      <template v-slot:index>{{ currImgIndex + 1+ '/' + imageList.length}}</template>
    </van-image-preview>
  </div>
</template>

<script>
import watermark from '@/assets/js/watermark.js'
import { ImagePreview } from 'vant'
export default {
  name: 'newsDetail',
  data () {
    return {
      loading: true,
      invalidForWechat: false,
      invalidForVisit: false,
      news: {},
      articleId: '',
      hasCollected: false,
      hasThumbUp: false,
      isMove: false, // 收藏动画
      isMove1: false, // 点赞动画
      isWxClient: false,
      startComment: false,
      msgContent: '',
      // 权限相关
      actionPermit: {
        showReadNumber: true,
        showCollect: false,
        showThumbUp: false,
        allowedThumbUp: false,
        allowedCollect: false,
        allowedComment: false,
        onlyFollower: false,
        forbidCopy: false,
        onlyWxClient: false,
        forbidForward: false,
        showWatermark: false
      },
      actionCount: {
        collectNum: 0,
        readNum: 0,
        thumbUpNum: 0,
        brushNum: 0
      },
      // 图片预览相关
      imageList: [],
      currImgIndex: 0,
      showPreview: false
    }
  },
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component
  },
  computed: {
    wechatName () {
      let wechatInfo = JSON.parse(localStorage.getItem('wechatInfo') || '{}')
      return wechatInfo.wechatName || ''
    }
  },
  methods: {
    onChange (index) {
      this.currImgIndex = index
    },
    previewImg (index) {
      console.log('index: ', index)
      this.currImgIndex = index
      this.showPreview = true
    },
    submitComment () {
      if (this.msgContent) {
        this.$_load.show()
        let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/send`
        let param = {
          msgContent: this.msgContent,
          nickName: localStorage.getItem('fansNickName') || '',
          openid: sessionStorage.getItem('openid'),
          wxAppid: sessionStorage.getItem('appid')
        }
        this.$post(url, param).then(res => {
          this.$_load.hide()
          this.cancelComment()
          if (res.code === 200) {
            this.$toast({
              message: '已提交，待平台审核'
            })
          }
        })
      }
      // this.cancelComment()
      // this.$toast({
      //   message: '已提交，待平台审核'
      // })
    },
    cancelComment () {
      this.msgContent = ''
      this.startComment = false
    },
    hideCommentBox () {
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    showCommentDialog () {
      this.checkAuth(() => {
        this.startComment = true
        setTimeout(() => {
          this.$refs.commentRef.focus()
        }, 0)
      })
      // this.startComment = true
      // setTimeout(() => {
      //   this.$refs.commentRef.focus()
      // }, 0)
    },
    praiseArticle () {
      this.checkAuth(() => {
        if (!this.hasThumbUp) {
          let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/thumbUp`
          let param = {
            cancel: false,
            nickName: localStorage.getItem('fansNickName') || '',
            openid: sessionStorage.getItem('openid'),
            wxAppid: sessionStorage.getItem('appid')
          }
          this.$post(url, param).then(res => {
            if (res.code === 200) {
              this.hasThumbUp = !this.hasThumbUp
              this.isMove1 = true
              setTimeout(() => {
                this.isMove1 = false
              }, 2000)
            }
          })
        } else {
          let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/thumbUp`
          let param = {
            cancel: true,
            nickName: localStorage.getItem('fansNickName') || '',
            openid: sessionStorage.getItem('openid'),
            wxAppid: sessionStorage.getItem('appid')
          }
          this.$post(url, param).then(res => {
            if (res.code === 200) {
              this.hasThumbUp = !this.hasThumbUp
            }
          })
        }
      })
      // if (!this.hasThumbUp) {
      //   this.hasThumbUp = !this.hasThumbUp
      //   this.isMove1 = true
      //   setTimeout(() => {
      //     this.isMove1 = false
      //   }, 2000)
      // } else {
      //   this.hasThumbUp = !this.hasThumbUp
      // }
    },
    collectArticle () {
      this.checkAuth(() => {
        if (!this.hasCollected) {
          let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/collect`
          let param = {
            cancel: false,
            nickName: localStorage.getItem('fansNickName') || '',
            openid: sessionStorage.getItem('openid'),
            wxAppid: sessionStorage.getItem('appid')
          }
          this.$post(url, param).then(res => {
            if (res.code === 200) {
              this.hasCollected = !this.hasCollected
              this.isMove = true
              setTimeout(() => {
                this.isMove = false
              }, 2000)
            }
          })
        } else {
          let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/collect`
          let param = {
            cancel: true,
            nickName: localStorage.getItem('fansNickName') || '',
            openid: sessionStorage.getItem('openid'),
            wxAppid: sessionStorage.getItem('appid')
          }
          this.$post(url, param).then(res => {
            if (res.code === 200) {
              this.hasCollected = !this.hasCollected
            }
          })
        }
      })
      // if (!this.hasCollected) {
      //   this.hasCollected = !this.hasCollected
      //   this.isMove = true
      //   setTimeout(() => {
      //     this.isMove = false
      //   }, 2000)
      // } else {
      //   this.hasCollected = !this.hasCollected
      // }
    },
    showQrCode () {
      window.eventBus.$emit('showWechatQr')
    },
    // 获取图文安全设置权限
    getArticlePermit () {
      let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/permit`
      let param = {}
      this.$get(url, param).then(res => {
        this.$_load.hide()
        this.loading = false
        if (res.code === 200) {
          if (res.data && res.data.actionPermit) {
            this.actionPermit = res.data.actionPermit
          }
          this.isWxClient = this.checkIfWxClient()
          // 只允许在微信环境打开
          if (this.actionPermit.onlyWxClient && !this.isWxClient) {
            this.invalidForWechat = true
            return false
          }
          // 如果只允许关注公众号的人访问
          if (this.actionPermit.onlyFollower) {
            if (this.checkIfSubscribe() !== 1) {
              this.invalidForVisit = true
              return false
            }
          }
          // 如果正文需要加水印
          if (this.actionPermit.showWatermark) {
            this.$nextTick(() => {
              watermark.set('罗氏诊断专属水印', document.querySelector('.news-detail'))
            })
          }
          // 如果禁止分享, 则不展示分享菜单
          if (this.actionPermit.forbidForward) {
            this.setCropToolMenuAndShare({
              showMenuList: [],
              forbitShare: true
            })
          // 否则设置分享参数
          } else {
            this.setCropToolMenuAndShare({
              shareInfo: {
                title: this.news.articleTitle,
                imgUrl: this.news.imagePath
              }
            })
          }
          // 埋点
          let trackData = {
            'action': 0,
            'mode': 'article',
            'page': '文章详情',
            'objId': this.articleId
          }
          this.articleId && this.userActionTrack(trackData)
          // 如果没有禁止复制正文，添加图片预览功能
          if (!this.actionPermit.forbidCopy) {
            this.$nextTick(() => {
              this.imageList = []
              // 获取所有img标签，并添加点击事件
              let imgs = Array.prototype.slice.call(document.querySelectorAll('img'))
              imgs.forEach((imgDOM, index) => {
                let src = imgDOM.getAttribute('src')
                this.imageList.push(src)
                imgDOM.addEventListener('click', this.previewImg.bind(this, index))
              })
            })
          }
        } else {
          this.$_load.hide()
        }
      })
    },
    // 获取
    getArticleAction () {
      let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}/action`
      let param = {
        openid: sessionStorage.getItem('openid') || '',
        wxAppid: sessionStorage.getItem('appid')
      }
      this.$get(url, param).then(res => {
        if (res.code === 200) {
          if (res.data && res.data.hasCollected) {
            this.hasCollected = res.data.hasCollected
          } else {
            this.hasCollected = false
          }
          if (res.data && res.data.hasThumbUp) {
            this.hasThumbUp = res.data.hasThumbUp
          } else {
            this.hasThumbUp = false
          }
        }
      })
    },
    init () {
      this.articleId = this.$route.params.articleId
      this.loading = true
      this.$_load.show()
      // 获取文章权限
      let url = `${this.SERVICE_PORTAL}/Knowledge/article/${this.articleId}`
      let params = {
        openid: sessionStorage.getItem('openid') || '',
        wxAppid: sessionStorage.getItem('appid')
      }
      this.$get(url, params).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.news = res.data
            this.news.content = this.getProxyForWxMat(this.news.content)
            // 获取阅读数据
            let actionCount = this.news.actionCount
            if (actionCount) {
              this.assignKey(this.actionCount, actionCount)
            }
            document.title = this.news.articleTitle
            // 获取图文的安全设置权限
            this.getArticlePermit()
            this.getArticleAction()
          } else {
            this.$_load.hide()
            this.$toast('该图文已删除')
          }
        } else {
          this.$_load.hide()
        }
      })
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang='stylus' scoped>
@keyframes mymove {
  0% {
    opacity 1
  }
  100% {
    top -20px
    opacity 0
  }
}
.dynamic
  position absolute
  left 0
  top 0
  opacity 0
  &.move
    animation mymove 2s 1
.news-wrapper
  max-width 700px
  margin auto
  .news-invalid-onlywechat,
  .news-invalid-visit
    text-align center
    padding-top 20px
    font-size 14px
  .news-detail
    position relative
    padding 10px 15px 15px
    &.noCopy
      user-select: none;
    .detail-title
      margin-bottom: 12px
      line-height: 1.4
      font-weight: 400
      font-size: 22px
    .detail-subtitle
      display flex
      flex-wrap wrap
      align-items center
      .sub-item
        margin 0 8px 10px 0
      .sub-icon
        padding: 2px 6px
        border: 1px solid rgba(0,0,0,0.2)
        color: rgba(0,0,0,0.3)
        font-size 12px
        border-radius 10px
      .sub-time, .sub-author
        color rgba(0,0,0,0.3)
        font-size: 14px
      .sub-wechat
        font-size: 14px
        color #607fa6
    .detail-footer
      display flex
      justify-content space-between
      align-items center
      margin-top 10px
      .detail-data
        display flex
        aling-items center
        .data-item
          display flex
          align-items center
          font-size 12px
          margin-right 15px
          .item-label
            color #8c8c8c
            margin-right 5px
          .item-content
            color #8c8c8c
      .detail-handle
        display flex
        align-items center
        font-size 12px
        .article-collect
          position relative
          color #C9CACA
          &.isCollected
            color #86CBBF
          .iconfont
            font-size 12px
            margin-right 3px
        .article-thumbUp
          position relative
          margin-left 20px
          color #C9CACA
          &.isThumbUped
            color #2FB3E3
          .iconfont
            font-size 12px
            margin-right 3px
  .detail-msg
    background #f2f2f2
    padding 30px 20px
    .msg-box
      background #fff
      padding 12px 10px
      border-radius 5px
      font-size 12px
      color #ccc
.article-comment-inputbox-wrapper
  position fixed
  bottom 0
  left 0
  right 0
  top 0
  z-index 200000
  background rgba(0,0,0,0.5)
  .article-comment-inputbox
    position absolute
    bottom 0
    left 0
    right 0
    height 260px
    background #fff
    padding 15px
    .inputbox-title
      position relative
      text-align center
      line-height 22px
      color #202125
      font-weight 600
      font-size 16px
      font-family 'PingFangSC-Semibold','PingFang SC'
      padding 0 0 14px 0
      .cancel-input
        position absolute
        right 0
        top 0
        width 22px
        height 22px
        background #F0F1F1
        color #071C43
        text-align center
        line-height 22px
        font-size 10px
        border-radius 50%
    .inputbox-content
      resize none
      border none
      appearance none
      background #F7F7F7
      height 150px
      line-height 1.5
      padding 10px
      box-sizing border-box
      &::-webkit-input-placeholder
        color rgba(51,51,51,0.3) !important
    .inputbox-submit
      line-height 36px
      text-align center
      background #C9CACA
      color #fff
      font-size 14px
      margin-top 10px
      &.active
        background #25679B
</style>
